package com.makingTeam.config.dataSource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * 设置数据源
 * 启动程序时，不要忘记将SpringBoot自动添加数据源进行排除哦，否则会报循环依赖问题。
 */
@Configuration
public class DataSourceConfig {


    @Bean
    @ConfigurationProperties("spring.datasource.dynamic.datasource.master")
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.dynamic.datasource.slave")
    public DataSource slaveDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource() {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        DataSource defaultMataSource = masterDataSource();
        objectObjectHashMap.put("master", defaultMataSource);
        objectObjectHashMap.put("slave", slaveDataSource());
        return new DynamicDataSource(defaultMataSource,objectObjectHashMap);

    }

}
